package factorytest.iflytek.com.einkiflytekfactorytest;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.PixelFormat;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;

import com.htfyun.eink.EinkUtils;

import factorytest.iflytek.com.einkiflytekfactorytest.common.LedCtrl;
import factorytest.iflytek.com.einkiflytekfactorytest.config.EinkProperty;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DebugLog;
import factorytest.iflytek.com.einkiflytekfactorytest.common.FTUtils;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.DisplayUtil;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.SystemPropertyUtil;
import factorytest.iflytek.com.einkiflytekfactorytest.utils.executor.AppExecutors;

/**
 * Created by sst on 2018/5/30.
 */

public class FTFloatWindowService extends Service {

    private static LinearLayout mFloatLayout = null;
    private WindowManager.LayoutParams wmParams;
    private WindowManager mWindowManager;
    private Button btnFactory;
    private Button btnUpdate;
    private static Button btnPCBA;

    private Context mContext;

    private final String PROPERTY_NO_FLOAT = "persist.ft.no_float";

    private MyBinder mBinder = new MyBinder();


    public class MyBinder extends Binder {
        public FTFloatWindowService getService() {
            return FTFloatWindowService.this;
        }
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        EinkProperty.setEinkFactoryTestEnabled(false);
        AppExecutors.runOnIoThread(TCONDisconnectedRunnable);
        FTUtils.startMainActivity(mContext);
    }

    @Override
    public IBinder onBind(Intent intent) {

        return mBinder;
    }

    @Override
    public boolean onUnbind(Intent intent) {

        return super.onUnbind(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        DebugLog.e( "onStartCommand:" + intent);

        if (isNoFloatEnabled()) {
            // 用于讯飞测试用.他们不想显示这个悬浮框
            stopSelf();
            return START_NOT_STICKY;
        }
        //一直开着这个浮动窗口
//        if (FTUtils.isFTPassed()) {
//
//            DebugLog.e( "Factory Test is passed, stopself");
//
//            stopSelf();
//            return START_NOT_STICKY;
//        }

        addFloatView();

        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        DebugLog.e( "onDestroy");

        EinkProperty.setEinkFactoryTestEnabled(false);

        removeFloatView();
    }

    private boolean isNoFloatEnabled() {
        String yes = SystemPropertyUtil.getSystemProperty(PROPERTY_NO_FLOAT);
        if (TextUtils.isEmpty(yes)) {
            return false;
        }
        return yes.equalsIgnoreCase("yes");
    }

    public static void setFloatLayoutShow(boolean show) {
        try {
            if (mFloatLayout != null) {
                mFloatLayout.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setFloatLayoutVisibility(int visibility) {
        try {
            if (mFloatLayout != null) {
                mFloatLayout.setVisibility(visibility);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setPCBABtnShow(boolean show) {
        try {
            if (btnPCBA != null) {
                btnPCBA.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private void removeFloatView() {
        if (mFloatLayout != null) {
            //移除悬浮窗口
            mWindowManager.removeView(mFloatLayout);

            btnUpdate.setOnTouchListener(null);

            btnUpdate.setOnClickListener(null);

            btnFactory.setOnClickListener(null);

            btnPCBA.setOnClickListener(null);

            mFloatLayout = null;
        }
    }

    private void addFloatView() {
        if (mFloatLayout != null) {
            return;
        }

        wmParams = new WindowManager.LayoutParams();
        //获取的是WindowManagerImpl.CompatModeWrapper
        mWindowManager = (WindowManager) getApplication().getSystemService(getApplication().WINDOW_SERVICE);
        //设置window type
        if (Build.VERSION.SDK_INT >= 24) { /*android7.0不能用TYPE_TOAST*/
            wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
        } else { /*以下代码块使得android6.0之后的用户不必再去手动开启悬浮窗权限*/
            String packname = mContext.getPackageName();
            PackageManager pm = mContext.getPackageManager();
            boolean permission = (PackageManager.PERMISSION_GRANTED == pm.checkPermission("android.permission.SYSTEM_ALERT_WINDOW", packname));
            if (permission) {
                wmParams.type = WindowManager.LayoutParams.TYPE_PHONE;
            } else {
                wmParams.type = WindowManager.LayoutParams.TYPE_TOAST;
            }
        }

        wmParams.setTitle("FT-FloatWindow");
        //设置图片格式，效果为背景透明
        wmParams.format = PixelFormat.RGBA_8888;
        //设置浮动窗口不可聚焦（实现操作除浮动窗口外的其他可见窗口的操作）
        wmParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;

        //设置悬浮窗口长宽数据
        wmParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
        wmParams.height = WindowManager.LayoutParams.WRAP_CONTENT;

        LayoutInflater inflater = LayoutInflater.from(getApplication());
        //获取浮动窗口视图所在布局
        mFloatLayout = (LinearLayout) inflater.inflate(R.layout.float_layout, null);


        mFloatLayout.measure(View.MeasureSpec.makeMeasureSpec(0,
                View.MeasureSpec.UNSPECIFIED), View.MeasureSpec
                .makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));

        //调整悬浮窗显示的停靠位置为左侧置顶
        wmParams.gravity = Gravity.LEFT | Gravity.START | Gravity.TOP;

        // 以屏幕左上角为原点，设置x、y初始值，相对于gravity
        wmParams.x = DisplayUtil.getScreenWidth(mContext) - mFloatLayout.getMeasuredWidth();
        wmParams.y = DisplayUtil.getScreenHeight(mContext) - mFloatLayout.getMeasuredHeight();

//        DebugLog.e(" wmParams.x = " +  wmParams.x);
//        DebugLog.e(" wmParams.y  = " +  wmParams.y );
//        DebugLog.e(" mFloatLayout.getMeasuredWidth()  = " +  mFloatLayout.getMeasuredWidth() );
//        DebugLog.e("mFloatLayout.getMeasuredHeight()  = " + mFloatLayout.getMeasuredHeight() );

        //添加mFloatLayout
        mWindowManager.addView(mFloatLayout, wmParams);

        //浮动窗口按钮
        btnFactory = (Button) mFloatLayout.findViewById(R.id.btnFactory);
        btnUpdate = (Button) mFloatLayout.findViewById(R.id.btnUpdate);
        btnPCBA = (Button) mFloatLayout.findViewById(R.id.btnPCBA);

        btnUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DebugLog.e("btnUpdate click");
                EinkUtils.forceEinkFullUpdateWithView(v);
            }
        });
//
        btnFactory.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                DebugLog.e("btnFactory click");
                FTUtils.startMainActivity(mContext);
            }
        });

        btnPCBA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DebugLog.e("btnPCBA click");
                FTUtils.startPCBAMainActivity(mContext);
            }
        });

        btnUpdate.setOnTouchListener(new FloatingOnTouchListener());
    }

    private class FloatingOnTouchListener implements View.OnTouchListener {
        private int x;
        private int y;

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    x = (int) event.getRawX();
                    y = (int) event.getRawY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    int nowX = (int) event.getRawX();
                    int nowY = (int) event.getRawY();
                    int movedX = nowX - x;
                    int movedY = nowY - y;
                    x = nowX;
                    y = nowY;
                    wmParams.x = wmParams.x + movedX;
                    wmParams.y = wmParams.y + movedY;

                    // 更新悬浮窗控件布局
                    mWindowManager.updateViewLayout(mFloatLayout, wmParams);

                    break;
                default:
                    break;
            }
            return false;
        }
    }

    private Runnable TCONDisconnectedRunnable = new Runnable() {

        private final String PREFIX = "persist.tcon_disconnected.";

        private int getIntValue(String propertyName, int defaultValue) {
            String val = SystemPropertyUtil.getSystemProperty(propertyName);
            if (TextUtils.isEmpty(val) || (!TextUtils.isDigitsOnly(val))) {
                return defaultValue;
            }

            return Integer.parseInt(val);
        }

        private int getRedOnCount() {

            return getIntValue(PREFIX + "redOnCount", 3);

        }

        private int getRedOnTime() {

            return getIntValue(PREFIX + "redOn", 400);

        }

        private int getRedOffTime() {
            return getIntValue(PREFIX + "redOff", 100);
        }

        private int getGreenOnCount() {

            return getIntValue(PREFIX + "greenOnCount", 2);

        }

        private int getGreenOnTime() {
            return getIntValue(PREFIX + "greenOn", 200);
        }

        private int getGreenOffTime() {
            return getIntValue(PREFIX + "greenOff", 80);
        }

        @Override
        public void run() {

            while (!EinkProperty.isTCONConnected()) {

                for (int i = 0; i < getRedOnCount(); i++) {
                    LedCtrl.setLedPriority(this, true, LedCtrl.LedAttr.led_red);
                    delayMs(getRedOnTime());

                    LedCtrl.setLedPriority(this, false, LedCtrl.LedAttr.led_green,  LedCtrl.LedAttr.led_red);
                    delayMs(getRedOffTime());
                }

                for (int i = 0; i < getGreenOnCount(); i++) {
                    LedCtrl.setLedPriority(this, true, LedCtrl.LedAttr.led_green);
                    delayMs(getGreenOnTime());

                    LedCtrl.setLedPriority(this, false, LedCtrl.LedAttr.led_green,  LedCtrl.LedAttr.led_red);
                    delayMs(getGreenOffTime());

                }

            }

            LedCtrl.setLedPriority(null, false, LedCtrl.LedAttr.led_green,  LedCtrl.LedAttr.led_red);

        }

        private void delayMs(int ms) {
            try {
                Thread.sleep(ms);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }
    };

}
